package com.example.backend.config;

import com.example.backend.domain.entity.Notification;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.NotificationChannel;
import com.example.backend.domain.enums.NotificationPriority;
import com.example.backend.domain.enums.NotificationStatus;
import com.example.backend.domain.enums.NotificationType;
import com.example.backend.domain.enums.Role;
import com.example.backend.repository.NotificationRepository;
import com.example.backend.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 通知示例数据生成器
 * 用于解决前端通知中心"加载数据出错"问题
 */
@Configuration
public class NotificationDataSeeder {

    @Bean
    @Transactional
    public CommandLineRunner initNotificationData(
            NotificationRepository notificationRepository,
            UserRepository userRepository) {
        return args -> {
            // 检查是否已有通知数据
            if (notificationRepository.count() > 0) {
                System.out.println("数据库已有通知数据，跳过示例数据生成");
                return;
            }

            System.out.println("开始生成示例通知数据...");

            // 获取用户
            List<User> admins = userRepository.findByRole(Role.ADMIN, Pageable.unpaged()).getContent();
            List<User> agents = userRepository.findByRole(Role.AGENT, Pageable.unpaged()).getContent();
            List<User> customers = userRepository.findByRole(Role.CUSTOMER, Pageable.unpaged()).getContent();

            if (admins.isEmpty() || agents.isEmpty() || customers.isEmpty()) {
                System.out.println("⚠️ 缺少必要的用户数据，请先运行用户初始化");
                return;
            }

            User admin = admins.get(0);
            User agent = agents.get(0);
            User customer = customers.get(0);

            Instant now = Instant.now();

            // 创建示例通知
            createNotification(notificationRepository, admin.getId(),
                    "🔧 系统维护通知",
                    "系统将于今晚22:00-02:00进行例行维护，期间可能无法正常访问，请提前保存工作内容。",
                    NotificationType.SYSTEM, NotificationPriority.HIGH, false, now.minus(2, ChronoUnit.HOURS));

            createNotification(notificationRepository, agent.getId(),
                    "🎫 新工单分配",
                    "您有一个新的高优先级工单需要处理：客户反馈登录问题",
                    NotificationType.TICKET, NotificationPriority.HIGH, false, now.minus(30, ChronoUnit.MINUTES));

            createNotification(notificationRepository, customer.getId(),
                    "✅ 工单处理完成",
                    "您的工单 #TICKET-000001 已处理完成，请查看处理结果并评价服务质量",
                    NotificationType.TICKET, NotificationPriority.NORMAL, false, now.minus(1, ChronoUnit.HOURS));

            createNotification(notificationRepository, admin.getId(),
                    "📊 每周数据报告",
                    "上周系统处理工单总数：156个，平均响应时间：2.3小时，客户满意度：4.7/5.0",
                    NotificationType.SYSTEM, NotificationPriority.NORMAL, true, now.minus(1, ChronoUnit.DAYS));

            createNotification(notificationRepository, agent.getId(),
                    "⏰ 工单即将超时",
                    "工单 #TICKET-000023 距离SLA截止时间还有2小时，请尽快处理",
                    NotificationType.TICKET, NotificationPriority.URGENT, false, now.minus(10, ChronoUnit.MINUTES));

            createNotification(notificationRepository, customer.getId(),
                    "🔄 工单状态更新",
                    "您的工单 #TICKET-000015 状态已更新为\"处理中\"，预计24小时内完成",
                    NotificationType.TICKET, NotificationPriority.NORMAL, true, now.minus(6, ChronoUnit.HOURS));

            createNotification(notificationRepository, admin.getId(),
                    "🚨 紧急：数据库连接异常",
                    "检测到数据库连接池连接数异常增长，请立即检查应用状态",
                    NotificationType.SYSTEM, NotificationPriority.URGENT, false, now.minus(5, ChronoUnit.MINUTES));

            createNotification(notificationRepository, agent.getId(),
                    "👤 新用户注册",
                    "用户\"李四\"已成功注册，等待账户激活审核",
                    NotificationType.SYSTEM, NotificationPriority.NORMAL, false, now.minus(20, ChronoUnit.MINUTES));

            createNotification(notificationRepository, customer.getId(),
                    "🎉 服务升级通知",
                    "我们的客服系统已升级，现在支持7x24小时在线服务和AI智能助手",
                    NotificationType.SYSTEM, NotificationPriority.LOW, true, now.minus(12, ChronoUnit.HOURS));

            createNotification(notificationRepository, admin.getId(),
                    "📈 性能监控提醒",
                    "系统CPU使用率达到85%，建议关注服务器性能",
                    NotificationType.SYSTEM, NotificationPriority.HIGH, false, now.minus(15, ChronoUnit.MINUTES));

            System.out.println("✅ 成功生成 " + notificationRepository.count() + " 条示例通知数据！");
        };
    }

    private void createNotification(NotificationRepository repository, Long userId, String title,
                                    String content, NotificationType type, NotificationPriority priority,
                                    boolean isRead, Instant createdAt) {
        Notification notification = Notification.builder()
                .userId(userId)
                .title(title)
                .content(content)
                .type(type)
                .priority(priority)
                .channel(NotificationChannel.IN_APP)
                .status(isRead ? NotificationStatus.READ : NotificationStatus.UNREAD)
                .createdAt(createdAt)
                .updatedAt(createdAt)
                .sentAt(createdAt)
                .readAt(isRead ? createdAt.plus(1, ChronoUnit.HOURS) : null)
                .build();

        repository.save(notification);
    }
}
